package com.iss.card.view.account.shake;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;

public class ShakeListener implements SensorEventListener {

	private static final int SPEED_SHRESHOLD = 1600;

	private static final int UPTATE_INTERVAL_TIME = 500;

	private SensorManager sensorManager;

	private Sensor sensor;

	private OnShakeListener onShakeListener;

	private Context mContext;

	private float lastX;
	private float lastY;
	private float lastZ;

	private long lastUpdateTime;

	public ShakeListener(Context c) {
		mContext = c;
		sensorManager = (SensorManager) mContext
				.getSystemService(Context.SENSOR_SERVICE);
		if (sensorManager != null) {

			sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
		}

		start();
	}

	public void start() {
		if (sensor != null) {
			sensorManager.registerListener(this, sensor,
					SensorManager.SENSOR_DELAY_GAME);
		}
	}

	public void stop() {
		sensorManager.unregisterListener(this);
	}

	public void setOnShakeListener(OnShakeListener listener) {
		onShakeListener = listener;
	}

	public void onSensorChanged(SensorEvent event) {
		long currentUpdateTime = System.currentTimeMillis();
		long timeInterval = currentUpdateTime - lastUpdateTime;
		if (timeInterval < UPTATE_INTERVAL_TIME)
			return;

		lastUpdateTime = currentUpdateTime;
		int sensorType = event.sensor.getType();
		float[] values = event.values;
		if (sensorType == Sensor.TYPE_ACCELEROMETER) {
			final int medumValue = 15;
			if (Math.abs(values[0]) > medumValue // x axis
					|| Math.abs(values[1]) > medumValue // y axis
					|| Math.abs(values[2]) > medumValue) { // z axis
				onShakeListener.onShake();
			}
		}

		// long currentUpdateTime = System.currentTimeMillis();
		//
		// long timeInterval = currentUpdateTime - lastUpdateTime;
		//
		// if (timeInterval < UPTATE_INTERVAL_TIME)
		// return;
		//
		// lastUpdateTime = currentUpdateTime;
		//
		// float x = event.values[0];
		// float y = event.values[1];
		// float z = event.values[2];
		//
		// float deltaX = x - lastX;
		// float deltaY = y - lastY;
		// float deltaZ = z - lastZ;
		//
		// lastX = x;
		// lastY = y;
		// lastZ = z;
		//
		// double speed = Math.sqrt(deltaX * deltaX + deltaY * deltaY + deltaZ
		// * deltaZ)
		// / timeInterval * 10000;
		//
		// if (speed >= SPEED_SHRESHOLD) {
		// onShakeListener.onShake();
		// }
	}

	public void onAccuracyChanged(Sensor sensor, int accuracy) {

	}

	public interface OnShakeListener {
		public void onShake();
	}

}